<!---添加采购食材-->
<template>
  <div>
    <cus-modal
      ref="modal"
      title="添加采购食材"
      :width="1280"
      @on-visible-change="onVisibleChange"
    >
      <Form :model="form" style="display: flex; justify-content: space-between">
        <FormItem label="供应商" :label-width="60" class="mr_48 mb_20">
          <Select
            v-model="form.supplyId"
            clearable
            disabled
            @on-change="
              postApiPurchasingSelectMaterialSupplyStatusListPageApi()
            "
            placeholder="全部"
            style="width: 200px"
          >
            <Option v-for="item in supplyTree" :value="item.id" :key="item.id">
              {{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="食材名称" :label-width="80" class="mr_48 mb_20">
          <Input
            v-model="form.ingredientsSelectName"
            maxlength="20"
            clearable
            style="width: 195px"
            placeholder="请输入食材名称"
          ></Input>
        </FormItem>
        <FormItem label="食材种类" :label-width="80" class="mr_48 mb_20">
          <Select
            placeholder="全部"
            v-model="form.foodClassName"
            clearable
            style="width: 195px"
          >
            <Option
              v-for="item in materialClassTree"
              :value="item.name"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <cusButton
          class="mr_10 mb_20"
          type="primary"
          @onClick="
            pages.page = 1;
            postApiPurchasingSelectMaterialSupplyStatusListPageApi();
          "
          >查询</cusButton
        >
      </Form>
      <Table
        border
        :loading="form.loading"
        :columns="columns"
        :data="data"
        :size="vuex_config.tableSize"
      >
        <template slot-scope="{ row }" slot="operation">
          <div class="flex">
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 5px"
              @onClick="onAdd(row)"
            >
              添加
            </cus-button>
          </div>
        </template>
      </Table>
      <div class="cus_page" v-if="data.length > 0">
        <cus-page
          :data="pages"
          class="mt_10"
          @pageChange="postApiPurchasingSelectMaterialSupplyStatusListPageApi"
        ></cus-page>
      </div>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer"></div>
        </slot>
      </div>
      <Spin size="large" fix v-if="loading"> </Spin>
    </cus-modal>
    <!--添加采购量-->
    <Modal v-model="modal" width="410" :title="form.ingredientsName" @on-visible-change="visibleChange">
      <Form
        :model="form"
        :label-width="130"
        ref="formValidate"
        @keydown.native.enter.prevent="onInit"
      >
        <FormItem label="计量单位">
          <Input v-model="form.model" disabled placeholder="请输入规格" />
        </FormItem>
        <FormItem label="单位重量(千克)">
          <Input
            v-model="form.modelWeight"
            disabled
            placeholder="请输入单位重量"
          />
        </FormItem>
        <FormItem label="价格(元)">
          <Input
            v-model="form.originalPrice"
            disabled
            placeholder="请输入食材价格"
          />
        </FormItem>
        <FormItem label="采购数量">
          <InputNumber
            :max="10000"
            :min="0"
            :precision="form.weightFlag=='是' ? 2 : 0"
            v-model="form.packagingQty"
            :active-change="false"
            @input="floatInput"
            style="width: 185px"
          />
        </FormItem>
        <FormItem label="金额(元)">
          <Input v-model="sum" disabled placeholder="请输入食材金额" />
        </FormItem>
      </Form>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer">
            <cus-button  size="small" @onClick="onCancel('two')"
              >取消</cus-button
            >
            <cus-button type="primary" size="small" @onClick="ok"
              >确认</cus-button
            >
          </div>
        </slot>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getApiPurchasingLocalfoodtypeList,
  postApiPurchasingSelectMaterialSupplyStatusListPage,
  postApiPurchasingInsertPoOrderDtl
} from "@/api/business/manager";

const form = {
  id: "",
  interId: "", //
  supplyId: "", //供应商id
  supplyName: "", //供应商名称
  ingredientsId: "", //食材编码
  ingredientsName: "", //食材名称
  ingredientsSelectName: "", //食材名称input查询框
  foodClassName: "", //食材种类
  model: "", //规格
  modelWeight: "", //单位重量
  originalPrice: "", //食材价格
  weightFlag: null, //是否称重标识
  packagingQty: 1 //采购量
};
const columns = [
  {
    //菜肴属性维护Table表头数据
    title: "序号",
    type: "index",
    width: 70,
    align: "center"
  },
  {
    title: "食材编码",
    minWidth: 100,
    key: "ingredientsId",
    align: "center"
  },
  {
    title: "食材名称",
    minWidth: 100,
    key: "ingredientsName",
    align: "center"
  },
  {
    title: "食材种类名称",
    minWidth: 120,
    key: "ingredientsTypeName",
    align: "center"
  },
  {
    title: "计量单位",
    minWidth: 100,
    key: "model",
    align: "center"
  },
  {
    title: "单位重量/公斤",
    minWidth: 130,
    key: "modelWeight",
    align: "center"
  },
  {
    title: "价格",
    minWidth: 100,
    key: "originalPrice",
    align: "center"
  },
  {
    title: "称重出入库",
    minWidth: 120,
    key: "weightFlag",
    align: "center"
  },
  {
    title: "品牌",
    minWidth: 100,
    key: "brand",
    align: "center"
  },
  {
    title: "操作",
    fixed: "right", // 右侧固定
    slot: "operation",
    align: "center",
    width: 135
  }
];
export default {
  components: {},
  data() {
    return {
      loading: false,
      form: form, //form表单
      materialClassTree: [], //食材种类数据
      supplyTree: "", //供应商数据select
      columns: columns, //表头
      data: [], //列表数据
      modal: false, //添加采购量m模态框状态
      // 分页
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      }
    };
  },

  mounted() {
    this.form = this.$cu.deepClone(form);
    this.form.supplyId = this.$route.query.supplyId
      ? this.$route.query.supplyId
      : this.form.supplyId;
  },
  methods: {
    visibleChange(v) {
      if(!v) {
        this.form.packagingQty = 1;
      }
    },
    onVisibleChange(v) {
      this.$refs["formValidate"].resetFields();
      if (!v) this.form = this.$cu.deepClone(form);
    },
    show() {
      this.loading = false;
      this.$refs["modal"].show = true;
      this.getApiPurchasingLocalfoodtypeListApi();
      this.postApiPurchasingSelectMaterialSupplyStatusListPageApi();
      console.log('供应商id',this.form.supplyId);
    },
    // 添加采购量
    onAdd(row) {
      console.log('ttt',row);
      this.form.weightFlag = row.weightFlag;
      this.form.id = row.id;
      this.form.ingredientsName = row.ingredientsName;
      this.form.ingredientsId = row.ingredientsId;
      this.form.model = row.model;
      this.form.modelWeight = row.modelWeight;
      this.form.originalPrice = row.originalPrice;
      if (row.model) this.modal = true;
    },
    // 处理两位小数
    floatInput(val) {
      console.log(val);
      let checkPlan = "" + val;
      checkPlan = checkPlan
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + "";
      } else if (checkPlan.indexOf(".") >= 0) {
        checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      }
      this.$nextTick(() => (this.form.packagingQty = checkPlan * 1));
      return checkPlan;
    },
    // 添加采购食材模态框确认
    onOk() {
      this.$refs["modal"].show = false;
    },
    // 取消
    onCancel(Flag) {
      if (Flag == "one") {
        this.$refs["modal"].onCancel();
      } else if (Flag == "two") this.modal = false;
      this.$refs["formValidate"].resetFields();
    },
    // 添加采购食材明细重量模态框确认
    ok() {
      if (this.form.packagingQty == 0) {
        this.$Message.info("采购数量不能为0!");
      } else {
        this.postApiPurchasingInsertPoOrderDtlApi();
      }
    },
    // 获取食材种类Select数据---------------------------接口
    getApiPurchasingLocalfoodtypeListApi() {
      return new Promise(resolve => {
        getApiPurchasingLocalfoodtypeList().then(res => {
          if (res.retCode == 2000) {
            console.log(res.data);
            this.materialClassTree = res.data;
            resolve();
          }
        });
      });
    },
    // 添加采购蔬菜列表-----------------------------------接口
    postApiPurchasingSelectMaterialSupplyStatusListPageApi() {
      return new Promise(resolve => {
        let params = {
          supplyId: this.form.supplyId, //添加采购明细默认id=1
          foodClassName: this.form.foodClassName, //食材种类
          ingredientsName: this.form.ingredientsName, //食材名称Form表单提交
          ingredientsName: this.form.ingredientsSelectName, //食材名称input框查询条件使用
          size: this.pages.pageSize,
          current: this.pages.page
        };
        postApiPurchasingSelectMaterialSupplyStatusListPage(params).then(
          res => {
            if (res.retCode == 2000) {
              console.log(res.data);
              this.data = res.data.records;
              this.data.forEach(element => {
                element.price = element.price; //价格
                element.originalPrice = element.originalPrice; // 包装价格
                element.weightFlag = element.weightFlag == 0 ? "否" : "是"; // 是否称重出入库，0否 1是
              });
              this.pages.pageTotal = res.data.total;
              resolve();
            }
          }
        );
      });
    },
    // 添加采购食材数据-----------------------------------接口
    postApiPurchasingInsertPoOrderDtlApi() {
      return new Promise(resolve => {
        let params = {
          ingredientsId: this.form.ingredientsId, //食材编码
          packagingQty: this.form.packagingQty, //采购重量
          interId: this.form.interId || 0 //供应商id
        };
        console.log("params", params);
        postApiPurchasingInsertPoOrderDtl(params).then(res => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.$parent.postApiPurchasingPoorderdtllistApi();
            this.onCancel("two");
            resolve();
          } else {
            this.modal = true;
          }
        });
      });
    }
  },
  computed: {
    //动态计算金额
    sum() {
      let amount =
        parseFloat(this.form.originalPrice) * parseFloat(this.form.packagingQty);
      return parseFloat(amount).toFixed(2) || 0;
    }
  },
  watch: {}
};
</script>

<style scoped></style>
